package com.apache.passport.service;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.api.api.ApiService;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.Validator;
import com.apache.exception.ServiceException;

/**
 * description:  单点登录服务
 * @author Hou Dayu 创建时间：2014-12-18  
 * @Copyright(c)2014:
 */
public class SsoServiceImpl implements ApiService {
	private static final Logger log = LoggerFactory.getLogger(SsoServiceImpl.class);

	private Map<String, PluginConnector> plugins;

	public ResultEntity doService(ParamsVo vo) throws ServiceException {
		ResultEntity result = new ResultEntity();
		result.setResult("true");
		String key = vo.getMethodKey();
		Object obj = plugins.get(key);
		if (Validator.isEmpty(obj)) {
			result.setEntity("F");
			result.setMessage("您访问的服务不存在或未启用");
			log.info("passport msg:[{}]", "您访问的服务不存在或未启用");
		} else {
			try {
				ResultEntity ent = null;
				boolean flag = false;
				//在操作前,首先执行下,当前访问的系统是否有权限支持
				if (plugins.get("checkSys").execute(vo) instanceof Boolean) {
					flag = (Boolean) plugins.get("checkSys").execute(vo);
				} else if (plugins.get("checkSys").execute(vo) instanceof ResultEntity) {
					ent = (ResultEntity) plugins.get("checkSys").execute(vo);
					String str = (String) ent.getEntity();
					if (!"F".equals(str)) {
						flag = true;
					}
				}
				if (flag) {
					return (ResultEntity) plugins.get(vo.getMethodKey()).execute(vo);
				} else if (!Validator.isEmpty(ent)) {
					return ent;
				} else {
					result.setEntity("O");
					log.info("passport msg:[{}]", "当前系统没有服务使用权限");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public void setPlugins(Map<String, PluginConnector> plugins) {
		this.plugins = plugins;
	}
}
